import React, { Component } from 'react'
import { connect } from 'dva';

import { Tree, Row, Col, Button, message } from 'antd';

const TreeNode = Tree .TreeNode;

export interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  tree: Array<any>,
  checked: string[],
  parentKeyMap: object,
  details: {
    name: string,
    id: number
  },
  history: any,
  match: {
    params: {
      id: string
    }
  }
}


@connect(({ role }) => ({
  tree: role.tree || [],
  parentKeyMap: role.parentKeyMap || {},
  checked: role.checked,
  details: role.details || {}
}))
class Authorization extends Component<IProps, any> {

  state = {
    current: 0,
    checkStrictly: true,
    childKeysList: [],
    parentKeysList: [],
    treeList: []
  };

  componentDidMount() {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'role/queryAuthById',
      payload: params.id
    })
  }

  renderTreeNodes(data = []) {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  }

  childKeys = (childTree) => {
    if(Array.isArray(childTree)) {
      childTree.forEach(item => {
        this.state.childKeysList.push(item.key);
        if(item.children && Array.isArray(item.children) && item.children.length > 0) {
          this.childKeys(item.children);
        }
      });
    }
  };

  forEachTree = (tree: any, selCheckedKeys) => {
    tree.forEach(treeItem => {
      if(treeItem.key !== selCheckedKeys) {
        if(treeItem.children && Array.isArray(treeItem.children) && treeItem.children.length > 0) {
          this.forEachTree(treeItem.children, selCheckedKeys);
        }
      }else {
        if(treeItem.children && Array.isArray(treeItem.children) && treeItem.children.length > 0) {
          this.state.childKeysList.push(treeItem.key);
          this.childKeys(treeItem.children);
        }
      }
    });
  };

  parentKeysMap = (tree, selCheckedParentKeys) => {
    tree.forEach(item => {
      if(item.key !== selCheckedParentKeys) {
        if(item.children && Array.isArray(item.children) && item.children.length > 0) {
          this.parentKeysMap(item.children, selCheckedParentKeys);
        }
      }else {
        this.state.parentKeysList.push(item.key);
        if(item.parentId !== 'ROOT') {
          selCheckedParentKeys = item.parentId;
          this.parentKeysMap(this.state.treeList, selCheckedParentKeys);
        }
      }
    });
  };

  onCheck = (checkedKeys, itemChecked) => {
    this.setState({
      checkStrictly: true
    });
    this.state.childKeysList = [];
    this.state.parentKeysList = [];
    const { dispatch, tree, parentKeyMap } = this.props;
    this.state.treeList = tree;
    let selCheckedParentKeys = parentKeyMap[itemChecked.node.props.eventKey];
    let selCheckedKeys = itemChecked.node.props.eventKey;
    this.parentKeysMap(tree, selCheckedParentKeys);
    this.forEachTree(tree, selCheckedKeys);
    let checkedKey = checkedKeys.checked;
    let checkedKeyList = [];
    if(itemChecked.checked) {
      checkedKeyList = [...checkedKey, ...this.state.childKeysList, ...this.state.parentKeysList]
    }else {
      this.state.childKeysList.forEach(listItem => {
        let index = checkedKey.findIndex((checkItem) => checkItem === listItem);
        if(index !== -1) {
          checkedKey.splice(checkedKey.findIndex((checkItem) => checkItem === listItem), 1);
        }
      });
      checkedKeyList = checkedKey;
    }
    dispatch({
      type: 'role/setChecked',
      payload: checkedKeyList
    });
  };

  handleSubmit = () => {
    const { dispatch } = this.props;
    let hasMsg = message.loading('');
    dispatch({ type: 'role/submitAuth' }).then(hasMsg);
  };

  render() {

    const { checked, details, tree } = this.props;

    return (
      <div>
        <Row>
          <Col span={12}>
            <h3>菜单权限</h3>
            <Tree
              checkable
              defaultExpandAll
              onCheck={this.onCheck}
              autoExpandParent={false}
              checkedKeys={checked}
              checkStrictly={this.state.checkStrictly}
            >
              { this.renderTreeNodes(tree) }
            </Tree>
          </Col>
          <Col span={12}>
            <h3>角色名称</h3>
            <p>{ details.name }</p>
            <h3>角色编号</h3>
            <p>{ details.id }</p>
            <Row>
              <Col span={6}><Button onClick={this.handleSubmit}>提交</Button></Col>
              <Col span={6}><Button onClick={() => this.props.history.go(-1)}>返回</Button></Col>
            </Row>
          </Col>
        </Row>
      </div>
    )
  }
}


export default Authorization;
